<template>
  <div class="table-query-data flex-v">
    <div class="title-bar space" style="margin-bottom: 0;">
      <div class="auto-flex">
        <strong>数据</strong>
      </div>
      <div v-if="curTable">
        <OpenFile></OpenFile>
        <button class="btn btn-sm btn-default"
          :class="['btn btn-sm btn-default', { active: ld.isShowRowIndex }]"
          @click="ld.isShowRowIndex ? delete ld.isShowRowIndex : (ld.isShowRowIndex = true)"
        >
          <i class="glyphicon glyphicon-list"></i>
          <span>显示序号</span>
        </button>
        <button class="btn btn-sm btn-default"
          :class="['btn btn-sm btn-default', { active: ld.isShowTableStructure }]"
          @click="cmd('库表结构')"
        >
          <i class="glyphicon glyphicon-tent"></i>
          <span>库表结构</span>
        </button>
        <!-- <button class="btn btn-sm btn-info"
          @click="cmd('复制')"
        >
          <i class="glyphicon glyphicon-copy"></i>
          <span>复制</span>
        </button> -->
        <button class="btn btn-sm btn-success"
          @click="cmd('添加一行')"
        >
          <i class="glyphicon glyphicon-plus"></i>
          <span>添加一行</span>
        </button>
        <button class="btn btn-sm btn-danger"
          @click="cmd('清空')"
        >
          <i class="glyphicon glyphicon-trash"></i>
          <span>清空</span>
        </button>
      </div>
    </div>
    <div class="auto-flex smooth-scroll" ref="scrollEl">
      <div class="ib space">
        <div class="flex-h" v-if="ld.isShowTableStructure && curTable" style="margin-bottom: 1.5em;">
          <div>
            <div v-if="scDB">
              <pre
                :class="{'text-danger bold': scDB?.endsWith('获取失败')}"
                @contextmenu="$root.copy(scDB)"
              >{{ scDB }}</pre>
            </div>
            <div v-if="scTable">
              <pre
                @contextmenu="$root.copy(scTable)"
              >{{ scTable }}</pre>
            </div>
          </div>
          <div v-if="curTable">
            <table class="table-data table-striped table-fix-thead">
              <thead>
                <tr>
                  <th>
                    <i
                      :class="['glyphicon glyphicon-' + (isFieldDisplayAll ? 'check' : 'unchecked')]"
                      @click="cmd('toggleCheckAll')"
                    ></i>
                  </th>
                  <th v-for="(v, idx) in fieldKeys" :key="idx">{{ v }}</th>
                  <th>
                    <button @click="$root.copy(field.list)" type="button" class="btn btn-xs btn-info">
                      <i class="glyphicon glyphicon-copy"></i>
                    </button>
                  </th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, idx) in field.list" :key="idx">
                  <td>
                    <i
                      :class="['glyphicon glyphicon-' + (row.display ? 'check' : 'unchecked')]"
                      @click="e => cmd('toggleCheck', row, e)"
                    ></i>
                  </td>
                  <td
                    v-for="(key, idxKey) in fieldKeys"
                    :key="idxKey"
                    @contextmenu="$root.copy(row[key])"
                    v-html="$parent.formatField_(row[key])"
                  ></td>
                  <td>
                    <button @click="$root.copy(row)" type="button" class="btn btn-xs btn-info">
                      <i class="glyphicon glyphicon-copy"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div v-if="curTable">
          <pre class="text-danger bold ib" @contextmenu="$root.copy(sqlSelect)">{{ sqlSelect }}</pre>
        </div>

        <NoData v-if="!curTable" :isLoading="field.isLoading"></NoData>

        <table v-if="curTable" class="table-data table-striped table-fix-thead table-fix-r table-sql-data">
          <thead class="unselect">
            <tr>
              <th v-if="ld.isShowRowIndex">序号</th>
              <th class="p" 
                v-for="(f, idx) in fields"
                :key="idx"
                @contextmenu="$root.copy(f)"
                @click="() => { f.sortCnt++; f.sortTime = Date.now(); $emit('lsData') }"
              >
                <div class="flex-h">
                  <div class="auto-flex">
                    <span>{{ f.Field }}</span>
                  </div>
                  <div>
                    <i v-if="f.sortCnt % 3" :class="['glyphicon glyphicon-arrow-' + (f.sortCnt % 3 > 1 ? 'down' : 'up')]"></i>
                    <el-popover trigger="click" width="auto">
                      <template #reference>
                        <i class="glyphicon glyphicon-filter"
                          @click.stop
                          :style="{ color: f.q ? $root.color.red : '' }"
                        ></i>
                      </template>
                      <form @submit.prevent="$emit('lsData')">
                        <textarea class="form-control" placeholder="筛选" 
                          v-if="['text', 'json'].includes(f.Type)"
                          v-model="f.q"
                          @change="$emit('ls-data')"
                        ></textarea>
                        <input placeholder="筛选" type="text" class="form-control"
                          v-else
                          v-model="f.q"
                          @change="$emit('ls-data')"
                        >
                      </form>
                    </el-popover>
                  </div>
                </div>
              </th>
              <th>
                <div class="flex-h">
                  <div class="auto-flex">
                    <span>操作</span>
                  </div>
                  <div>
                    <button class="btn btn-xs btn-info"
                      @click="$root.copy(data.list)"
                    >
                      <i class="glyphicon glyphicon-copy"></i>
                    </button>
                    <el-tooltip v-if="fields.filter(v => v.q).length > 0" placement="top">
                      <template #content>
                        <div style="padding: .5em;">去掉筛选条件</div>
                      </template>
                      <button class="btn btn-xs btn-danger"
                        @click="() => { fields.forEach(v => v.q = ''); $emit('ls-data') }"
                        style="vertical-align: top;" 
                      >
                        <i class="glyphicon glyphicon-ban-circle"></i>
                      </button>
                    </el-tooltip>
                  </div>
                </div>
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="!data.list.length">
              <td :colspan="fields.length + 1 + !!ld.isShowRowIndex">
                <NoData :isLoading="data.isLoading" style="text-align: left;"></NoData>
              </td>
            </tr>
            <tr
              v-for="(row, idxRow) in data.list"
              :key="idxRow"
            >
              <td v-if="ld.isShowRowIndex">{{ (page.cur - 1) * page.size + idxRow + 1 }}</td>
              <td
                v-for="(f, idx) in fields"
                :key="idx"
                @contextmenu="$root.copy(row[f.Field])"
              >
                <SmartToolTip :content="row[f.Field]"></SmartToolTip>
              </td>
              <td>
                <button class="btn btn-xs btn-info"
                  @click="cmdRow('复制行', row)"
                >
                  <i class="glyphicon glyphicon-copy"></i>
                </button>
                <button class="btn btn-xs btn-success"
                  @click="cmdRow('查看行', row)"
                >
                  <i class="glyphicon glyphicon-eye-open"></i>
                </button>
                <button class="btn btn-xs btn-warning"
                  @click="cmdRow('编辑行', row)"
                >
                  <i class="glyphicon glyphicon-pencil"></i>
                </button>
                <button class="btn btn-xs btn-danger"
                  @click="cmdRow('删除行', row)"
                >
                  <i class="glyphicon glyphicon-trash"></i>
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="glb block c">
      <el-pagination
        v-model:current-page="page.cur"
        v-model:page-size="page.size"
        :page-sizes="[20, 30, 50, 100, 200, 300, 500, 1000]"
        :small="true"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @current-change="cur => { page.cur = cur; $emit('lsData') }"
        @size-change="size => { page.cur = 1; page.size = size; $emit('lsData') }"
      />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {}
  },
  computed: {
    r() {
      return this.$root.router
    },
    ld() {
      return this.$root.ld
    },
    field() {
      return this.$parent.field
    },
    page() {
      return this.$parent.page
    },
    data() {
      return this.$parent.data
    },
    curTable() {
      return this.$parent.curTable
    },
    scDB() {
      return this.$parent.scDB
    },
    scTable() {
      return this.$parent.scTable
    },
    fieldKeys() {
      return this.$parent.fieldKeys
    },
    fields() {
      return this.$parent.fields
    },
    isFieldDisplayAll() {
      return this.field.list.every(v => v.display)
    },
    dbTable() {
      return this.$parent.dbTable
    },
    sqlSelect() {
      const where = this.fields.filter(v => v.q).map(v => `${v.Field}='${v.q.replaceAll(`'`, `\\'`)}'`).join(' ')
      const orderBy = this.fields.filter(v => v.sortCnt % 3).map((v) => {
        return v.Field + ' ' + ['', 'ASC', 'DESC'][v.sortCnt % 3]
      }).join(' ')

      return `SELECT * FROM ` + this.dbTable + (where ? ' WHERE ' + where : '') + (orderBy ? ' ORDER BY ' + orderBy : '')
    }
  },
  methods: {
    runSql(sql) {
      return this.$parent.runSql(sql)
    },
    async cmd(a, arg, e) {
      const ld = this.ld

      switch (a) {
        case 'toggleCheck':
          if (e.altKey) {
            this.field.list.forEach(v => v.display = !v.display)
          } else {
            arg.display = !arg.display
          }
          break
        case 'toggleCheckAll':
          {
            const isAll = this.isFieldDisplayAll
            this.field.list.forEach(v => v.display = !isAll)
          }
          break
        case 'showFilter':
          console.log('showFilter', arg)
          break
        case '库表结构':
          ld.isShowTableStructure ? delete ld.isShowTableStructure : (ld.isShowTableStructure = true);
          if (ld.isShowTableStructure) this.$refs.scrollEl.scrollTop = 0
          break
        case '复制':
          vm.copy(this.data.list)
          break
        case '添加一行':
          console.log('添加一行')
          break
        case '清空':
          {
            const sql = `TRUNCATE TABLE ${ this.dbTable }`
            await this.$confirm(`确定要执行 ${sql} 吗？`, '提示', { type: 'warning' })
            await this.runSql(sql)
          }
          break
      }
    },
    async cmdField(a, row) {
      switch (a) {
        case '编辑字段':
          console.log('编辑字段')
          break
        case '删除字段':
          console.log('删除字段')
          break
      }
    },
    async cmdRow(a, row) {
      switch (a) {
        case '复制行':
          vm.copy(row)
          break
        case '查看行':
          console.log('查看行')
          break
        case '编辑行':
          console.log('编辑行')
          break
        case '删除行':
          console.log('删除行')
          break
      }
    },
  },
  async mounted() {
    // console.log(this)
    window.com = this
  }
}
</script>

<style lang="less" scoped>
.table-query-data {}
</style>